﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Resources;

namespace LAPSac
{
    public partial class LAPSacForm : Form
    {
        public LAPSacForm()
        {
            InitializeComponent();
            dateTimePicker1.Value = DateTime.Now.AddHours(18);
        }
        public LAPSacForm(string[] myArgs)
        {
            InitializeComponent();
            textBoxCN.Text = myArgs[0];
            search();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Search");
            button2.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Set");
            button3.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Exit");
            label1.Text = LAPSac.Properties.Resources.ResourceManager.GetString("ComputerName");
            label2.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Password");
            label3.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Passwordexpires");
            label4.Text = LAPSac.Properties.Resources.ResourceManager.GetString("New expiration time");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            search();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
            {

                search();
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            setpassword();
        }

        private void search()
        {
            if (!string.IsNullOrWhiteSpace(textBoxCN.Text))
            {
                const int LDAPPort = 389;

                using (LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().Name, LDAPPort)))
                {
                    ldap.SessionOptions.LocatorFlag = LocatorFlags.DirectoryServicesRequired | LocatorFlags.WriteableRequired;
                    ldap.SessionOptions.ReferralChasing = ReferralChasingOptions.All;
                    ldap.SessionOptions.Sealing = true;
                    ldap.SessionOptions.Signing = true;
                    ldap.SessionOptions.SecureSocketLayer = true;
                    SearchRequest adSearch = new SearchRequest();
                    adSearch.Filter = (string.Format("(&(objectClass=computer)(|(cn={0})(dNSHostName={0})))", textBoxCN.Text));
                    adSearch.Scope = System.DirectoryServices.Protocols.SearchScope.Subtree;
                    adSearch.Attributes.Add("ms-Mcs-AdmPwd");
                    adSearch.Attributes.Add("ms-Mcs-AdmPwdExpirationTime");
                    adSearch.Attributes.Add("cn");
                  
                    SearchResponse sr = (SearchResponse)ldap.SendRequest(adSearch);


                    if (sr.Entries.Count > 0)
                    {
                        toolStripStatusLabel1.Text = string.Format("Computer found {0}", sr.Entries[0].DistinguishedName);
                        
                        if (sr.Entries[0].Attributes.Contains("ms-Mcs-AdmPwd"))
                        {
                            var admPWD = sr.Entries[0].Attributes["ms-Mcs-AdmPwd"][0].ToString();
                            textBoxPassword.Text = admPWD.ToString();
                        }
                        else textBoxPassword.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Passwordnotfoundoraccessdenied");
                        if (sr.Entries[0].Attributes.Contains("ms-Mcs-AdmPwdExpirationTime"))
                        {
                            var date = sr.Entries[0].Attributes["ms-Mcs-AdmPwdExpirationTime"][0].ToString();
                            long fileTime = long.Parse(date, System.Globalization.NumberFormatInfo.InvariantInfo);

                            textBoxPasswordExpires.Text = DateTime.FromFileTime(fileTime).ToString();
                        }
                        else textBoxPasswordExpires.Text = LAPSac.Properties.Resources.ResourceManager.GetString("PasswordExpirationnotfound");                         
                    }
                    else
                    {
                        textBoxPassword.Text = "";
                        textBoxPasswordExpires.Text = "";
                    }

                }
            }
        }

        private void setpassword()
        {
            if (!string.IsNullOrWhiteSpace(textBoxCN.Text))
            {

                DirectoryEntry rootDSE = new DirectoryEntry();
                rootDSE.AuthenticationType = AuthenticationTypes.Secure & AuthenticationTypes.Sealing & AuthenticationTypes.Signing;
                rootDSE.Path = "LDAP://RootDSE";
                string defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();

                using (var userBinding = new DirectoryEntry())
                {
                    userBinding.AuthenticationType = AuthenticationTypes.Secure & AuthenticationTypes.Sealing & AuthenticationTypes.Signing;
                    userBinding.Path = "LDAP://" + defaultNamingContext;
                    using (DirectorySearcher adSearch = new DirectorySearcher(userBinding))
                    {
                        
                        adSearch.ReferralChasing = ReferralChasingOption.All;
                        adSearch.Filter = (string.Format("(&(objectClass=computer)(|(cn={0})(dNSHostName={0})))", textBoxCN.Text));

                        var result = adSearch.FindOne();
                        if (result != null)
                        {
                            DateTime dtToBeSet = dateTimePicker1.Value;
                            if (DateTime.Now.AddMinutes(2) > dtToBeSet) dtToBeSet = DateTime.Now.AddMinutes(2);
                            try
                            {
                                DirectoryEntry de = new DirectoryEntry(result.Path);
                                de.AuthenticationType = AuthenticationTypes.Secure & AuthenticationTypes.Sealing & AuthenticationTypes.Signing;
                                de.Properties["ms-Mcs-AdmPwdExpirationTime"].Value = dtToBeSet.ToFileTime().ToString(); 
                                de.CommitChanges();
                                toolStripStatusLabel1.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Successfullychanged");
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.ToString());
                                toolStripStatusLabel1.Text = LAPSac.Properties.Resources.ResourceManager.GetString("Errorchanging");
                            }
                        }
                    }
                }
            }
        }

    }
}
